package com.ly.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ly.mapper.*;
import com.ly.po.ExamCoursePO;
import com.ly.po.ExamPO;
import com.ly.pojo.Courses;
import com.ly.pojo.Exam;
import com.ly.query.ExamQuery;
import com.ly.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
@Transactional
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private TeachersMapper teachersMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private SelectionsMapper selectionsMapper;

    @Override
    public ExamPO getExamPOByCourseId(int courseId) {
        return examMapper.selectPOByCourseId(courseId);
    }

    @Override
    public int insertExam(Exam exam) {
        exam.setExamCode(exam.getCourseCode() + exam.getStartTime());
        Exam exam1 = examMapper.selectByExamCode(exam.getCourseCode() + exam.getStartTime());
        if (exam1 == null) {
            return examMapper.insert(exam);
        }

        return examMapper.updateByExamCode(exam);
    }

    @Override
    public int updateExam(ExamPO examPO) {
        Exam exam = new Exam();
        exam.setExamCode(examPO.getCourseCode() + System.currentTimeMillis());
        exam.setCourseCode(examPO.getCourseCode());
        exam.setStartTime(examPO.getExamStartTime());
        exam.setEndTime(examPO.getExamEndTime());
        if (examPO.getState() == null) {
            exam.setState(1);
        } else {
            exam.setState(examPO.getState());
        }
        return examMapper.updateByCourseCode(exam);
    }

    @Override
    public PageInfo<ExamPO> getAllExam(int page, int size) {
        PageHelper.startPage(page, size);

        List<ExamPO> examPOList = examMapper.selectPOAll();

        PageInfo<ExamPO> pageInfo = PageInfo.of(examPOList);
        return pageInfo;
    }

    @Override
    public PageInfo<ExamPO> getAllExamByStudent(Long sno, int page, int size) {
        // 只获取当前学期的
        PageHelper.startPage(page, size);

        //根据sno获得学生id（student表）
        Integer studentId = studentsMapper.selectIdBySno(sno);
        //根据学生id获得课程id集合(selection表)
        List<Integer> courseIds = selectionsMapper.selectCourseIdsByStudentId(studentId);
        //根据课程id集合获得课程代码集合
        List<String> courseCodes = new ArrayList<>();
        for (Integer courseId : courseIds) {
            String courseCode = coursesMapper.selectCourseCodeByIdPO(courseId);
            courseCodes.add(courseCode);
        }


        // 根据course_code集合获得examPO集合（exam表）
        //List<ExamPO> examPOList = examMapper.selectPOAllByCourseCodes(courseCodes);
        // 只获取当前学期的
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1; // 1-12月

        String semesterTmp;
        if (month >= 2 && month <= 7) {
            // 2月-7月为春季学期
            semesterTmp = "春季学期";
        } else {
            // 8月-次年1月为秋季学期
            semesterTmp = "秋季学期";
            // 如果当前是8月-12月，年份不变；如果是1月，年份需要减1
            if (month == 1) {
                year--;
            }
        }
        String semester = year + "年" + semesterTmp;


        List<ExamPO> examPOList = examMapper.selectPOByCourseCodesAndSemester(courseCodes, semester);

        PageInfo<ExamPO> pageInfo = PageInfo.of(examPOList);
        return pageInfo;
    }

    @Override
    public int deleteExamByCourseId(int courseId) {
        String courseCode = coursesMapper.selectCourseCodeByIdPO(courseId);
        return examMapper.deleteByCourseCode(courseCode);
    }

    @Override
    public int containtCourse(int courseId, Long tno) {
        //根据tno找到所对应的courseid集合
        Integer teacherId = teachersMapper.selectIdByTno(tno);
        List<Integer> courseIds = coursesMapper.selectIdByTeacherId(teacherId);
        //遍历该集合
        //判断是否和courseId相等，只要有相等的就OK
        for (Integer id : courseIds) {
            if (id == courseId) {
                return 0;
            }
        }
        return 1;
    }

    @Override
    public Exam getExamByCourseCode(String courseCode) {
        return examMapper.selectByCourseCode(courseCode);
    }

    @Override
    public int deleteExamByCourseCode(String courseCode) {
        return examMapper.deleteByCourseCode(courseCode);
    }

    @Override
    public void deleteExamByCourseCodeList(List<String> courseCodeList) {
        for (String courseCode : courseCodeList) {
            examMapper.deleteByCourseCode(courseCode);
        }
    }

    @Override
    public Page<ExamCoursePO> getAllExams(ExamQuery query) {
        // 查询数据
        List<ExamCoursePO> exams = examMapper.selectAllExams(query);

        // 查询总数
        long total = examMapper.countAllExams(query);

        return new PageImpl<>(exams, PageRequest.of(query.getPage() - 1, query.getSize()), total);
    }

    @Override
    public PageInfo<ExamPO> getAllExamByCourseList(int page, int size, List<Courses> coursesList) {
        /*
        // 需要根据教师tno查询到所有相关的ExamCoursePO
        // 在course表，使用tno拿到course（courseCode，semester，courseName）
        // 在exam表，使用courseCode拿到exam（startTime，endTime，state）
        // 在cultivate表，使用courseCode拿到classCode，semester
        // 在t_class表，使用classCode拿到className，college，major
         */
        /*
            遍历courseList，对于对于每一个courseCode进行查询，结果
            一个课程代码对应一个考试数据
            拿到exam表的startTime，endTime，state
            联表courses，然后拿课程代码去拿courseCode，semester，courseName
            联合cultivate，classCode，semester
            联合t_class，className，college，major
         */
        PageHelper.startPage(page, size);

        List<ExamPO> examsList = new ArrayList<>();
        for (Courses courses : coursesList) {
            ExamPO exams = examMapper.selectExamsByCourseCode(courses.getCourseCode());
            if (exams != null) {
                System.out.println(exams);
                examsList.add(exams);
            }
        }
        System.out.println(examsList);

        PageInfo<ExamPO> pageInfo = PageInfo.of(examsList);
        return pageInfo;
    }
}
